<?php
/**
 * Created by PhpStorm.
 * User: wei
 * Date: 2016/2/17
 * Time: 14:48
 */
//分页方法
function pagelei($page,$count, $limit)
{
    $data=array();
    $page=(int)$page;
    $maxPage=ceil($count/$limit);
    $page<1?$page=1:'';
    $page>$maxPage?$page=$maxPage:'';
    $data['offset']=($page-1)*$limit;
    $data['maxPage']=$maxPage;
    $data['page']=$page;
    return $data;
}

//获取随机字符串
function getRandChar($length){
    $str = null;
   // $strPol = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
    $strPol = "0123456789";
    $max = strlen($strPol)-1;

    for($i=0;$i<$length;$i++){
        $str.=$strPol[rand(0,$max)];//rand($min,$max)生成介于min和max两个数之间的一个随机整数
    }

    return $str;
}

//验证用户是否登录
function verifyKey($username,$key){
    S(array('type'=>'redis'));
    $userKey=S($username.C('KEY_POSTFIX'));
    if($key==$userKey){
        return true;
    }else{
        return false;
    }
}

function user_score_sum($uid){

    $sum=D("PScoreRecord")->query('select sum(consume) as consume from zsf_p_score_record where is_deleted=0 and consume>0 and expire_time>='.time().' and type in (1,2,5,6,7) and user_id = '.$uid);
    $sum=$sum[0]['consume'];
    if(empty($sum))
        $sum=0;
    return $sum;
    //积分类型：1报名2导入3兑换4抽奖5分享 6为签到,7为连续签到
}

function consume_score($uid,$total_score){
    if($total_score<1)return;
    $list=D("PScoreRecord")
        ->field('id,consume')
        ->where('is_deleted','=',0)
        ->where('expire_time','>=',time())
        ->where('consume','>',0)
        ->where('type','in',[1,2,5,6,7])
        ->where('user_id','=',$uid)->order('expire_time asc,id asc')->select();


    foreach ($list as $k => $v) {

        $where['id']=$v['id'];
        if($v['consume']>=$total_score){
            $list[$k]['consume']=$v['consume']-$total_score;
            $total_score=0;
        }
        else{
            $list[$k]['consume']=0;
            $total_score=$total_score-$v['consume'];
        }
        D("PScoreRecord")->where($where)->save($list[$k]);

        if($total_score<1)break;
    }
}

/**
 * 检测当前登录用户是否有操作权限
 * @param  int $cid 分类id
 * @param  string $user_name
 * @param  string $key
 * @param  string $rid 当前登录角色类型
 * @param  bool 当前页面允许操作角色类型 true为允许普通用户操作,false为只能为师傅登录角色操作
 * @return $data array
 * @author lyz
 */
function checkRole($phone, $key, $rid=1, $flag = false){
    S(array('type' => 'redis'));
    if (S($phone . C('KEY_POSTFIX')) != $key) {		
        $data = array(code => 1004, msg => 'key不对应,请重新登录');
        //return $data;
    }
    $user = M('user');
    $map['phone'] = $phone;
    $userInfo = $user->where($map)->find();
    $data=array('code'=>200,'msg'=>'success');
    if (!empty($userInfo)) {
        if ($flag && ($userInfo['identity'] == 1)) {
            $data = array('code' => 1005, 'msg' => '当前登录角色不为师傅，请重新切换角色进行操作');
        }
        if ($rid != $userInfo['identity']) {
            $data = array('code' => 1007, 'msg' => '当前登录角色身份不一致');
        }
    } else {
        $data = array('code' => 1006, 'msg' => '用户不存在，请重新登录');
    }
    return $data;
}

function echoHeader(){
    if(true){
      return  header("Access-Control-Allow-Origin: *");
    }
}


/**
 * @return string
 * 输出周几
 */
function week(){
    $ga = date("w");
    switch( $ga ){
        case 1 : return "星期一";break;
        case 2 : return "星期二";break;
        case 3 : return "星期三";break;
        case 4 : return "星期四";break;
        case 5 : return "星期五";break;
        case 6 : return "星期六";break;
        case 0 : return "星期日";break;
        default : echo "你输入有误！";
    };
}


/**
 * @return int
 * 获取今天凌晨的时间戳
 */

function getTodayTime(){
    $y=date('Y');
    $m=date('m');
    $d=date('d');
    return mktime(0,0,0,$m,$d,$y);
}


function workTime($date){
    $time = (int) substr($date, 0, 10);
    $int = time() - $time;
    $str = '';
    if ($int <= 2){
        $str = sprintf('刚刚', $int);
    }elseif ($int < 60){
        $str = sprintf('%d秒前', $int);
    }elseif ($int < 3600){
        $str = sprintf('%d分钟前', floor($int / 60));
    }elseif ($int < 86400){
        $str = sprintf('%d小时前', floor($int / 3600));
    }elseif ($int < 2592000){
        $str = sprintf('%d天前', floor($int / 86400));
    }else{
        $str = date('Y-m-d H:i:s', $time);
    }
    return $str;
}



/**
 * 发送HTTP请求方法
 * @param  string $url    请求URL
 * @param  array  $params 请求参数
 * @param  string $method 请求方法GET/POST
 * @return array  $data   响应数据
 */
function http($url, $params, $method = 'GET', $header = array(), $multi = false){
    $opts = array(
        CURLOPT_TIMEOUT        => 30,
        CURLOPT_RETURNTRANSFER => 1,
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_SSL_VERIFYHOST => false,
        CURLOPT_HTTPHEADER     => $header
    );
    /* 根据请求类型设置特定参数 */
    switch(strtoupper($method)){
        case 'GET':
            $opts[CURLOPT_URL] = $url . '?' . http_build_query($params);
            break;
        case 'POST':
            //判断是否传输文件
            $params = $multi ? $params : http_build_query($params);
            $opts[CURLOPT_URL] = $url;
            $opts[CURLOPT_POST] = 1;
            $opts[CURLOPT_POSTFIELDS] = $params;
            break;
        default:
            throw new Exception('不支持的请求方式！');
    }
    /* 初始化并执行curl请求 */
    $ch = curl_init();
    curl_setopt_array($ch, $opts);
    $data  = curl_exec($ch);
    $error = curl_error($ch);
    curl_close($ch);
    if($error) throw new Exception('请求发生错误：' . $error);
    return  $data;
}





/**
 * @desc 根据两点间的经纬度计算距离
 * @param float $lat 纬度值
 * @param float $lng 经度值
 */
function getDistance($lat1, $lng1, $lat2, $lng2)
{
    $earthRadius = 6367000; //approximate radius of earth in meters

    /*
    Convert these degrees to radians
    to work with the formula
    */

    $lat1 = ($lat1 * pi() ) / 180;
    $lng1 = ($lng1 * pi() ) / 180;

    $lat2 = ($lat2 * pi() ) / 180;
    $lng2 = ($lng2 * pi() ) / 180;

    /*
    Using the
    Haversine formula

    http://en.wikipedia.org/wiki/Haversine_formula

    calculate the distance
    */

    $calcLongitude = $lng2 - $lng1;
    $calcLatitude = $lat2 - $lat1;
    $stepOne = pow(sin($calcLatitude / 2), 2) + cos($lat1) * cos($lat2) * pow(sin($calcLongitude / 2), 2);
    $stepTwo = 2 * asin(min(1, sqrt($stepOne)));
    $calculatedDistance = $earthRadius * $stepTwo;

    return round($calculatedDistance);
}


/**
 * jpush(消息存入redis)
 */

function jpushStr($alias,$content,$type='',$data='',$m_time=600){
    $messageData=array();
    $messageData['alias']=$alias;
    $messageData['content']=$content;
    $messageData['type']=$type;
    $messageData['data']=$data;
    $messageData['m_time']=$m_time;
    $str=serialize($messageData);
    $redis = S(array('type' => 'redis'));
    $a=$redis->lpush(C('JPUSH_KEY'), $str);
}